package com.cb.controller.front.order;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import webservices.alipaydirect.util.AlipayNotify;

import com.cb.common.enumType.OrderStatus;
import com.cb.common.map.BOrderCommon;
import com.cb.core.controller.BaseListController;
import com.cb.domain.model.order.BOrder;
import com.cb.domain.service.order.BOrderManager;

/**
 * 
 * @Author author
 * @Vesion 1.0 Create Time:
 *         <p>
 *         <b>Class Description:</b>[TODO]
 *         <p>
 */

public class TradeResultController extends BaseListController {

	@Autowired
	private BOrderManager bOrderManager;

	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");

//			valueStr=java.net.URLDecoder.decode(valueStr,"utf-8"); 
			/*if(name.equalsIgnoreCase("body")||name.equalsIgnoreCase("subject")){
				valueStr=java.net.URLDecoder.decode(valueStr,"utf-8"); 
			}*/
			params.put(name, valueStr);
		}
		System.out.println(params.toString());
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

		String trade_no = request.getParameter("trade_no");				//支付宝交易号
		String order_no = request.getParameter("out_trade_no");	        //获取订单号
		String total_fee = request.getParameter("total_fee");	        //获取总金额
		String subject=request.getParameter("subject");
//		String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"utf-8");//商品名称、订单名称
		String body = request.getParameter("body");
		
//		payment_type
		/*if(request.getParameter("body") != null){
			body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "utf-8");//商品描述、订单备注、描述
		}*/
		String buyer_email = request.getParameter("buyer_email");		//买家支付宝账号
		String trade_status = request.getParameter("trade_status");		//交易状态
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		Boolean result;
		BOrder bOrder= bOrderManager.findOrderByNo(order_no);
		System.out.println(verify_result);
//		if(verify_result){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				
				bOrder.setPayChannel("支付宝");
				total_fee="1";
				bOrder.setStatus(BOrderCommon.getOrderStatusMap().get(
						OrderStatus.PAY_OK));
				bOrder.setNoPay(bOrder.getNoPay()-Long.valueOf(total_fee));
				bOrder.setTradeNo(trade_no);
//			}
			
			result=true;
		}else{
			bOrder.setPayStatus(null);
			result=false;
		}
		bOrderManager.save(bOrder);
		ModelMap modelMap=new ModelMap();
		modelMap.addAttribute("result", result);
		modelMap.addAttribute("order", bOrder);
		
		return new ModelAndView("/front/order/returnurl").addAllObjects(modelMap);

	}
}
